
/**
 * @program: LeetCode
 * @description: LeetCode : 剑指 Offer 68 - II. 二叉树的最近公共祖先
 * @author: WXY
 * @create: 2022-12-11 16:10
 * @Version 1.0
 **/


public class Num068_2_lowestCommonAncestor {
    public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;
        return process(root, p, q).ans;
    }

    private static Info process(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return new Info(null, false, false);
        }
        Info leftInfo = process(root.left, p, q);
        Info rightInfo = process(root.right, p, q);
        boolean findP = root == p || leftInfo.findP || rightInfo.findP;
        boolean findQ = root == q || leftInfo.findQ || rightInfo.findQ;
        TreeNode ans = null;
        if (leftInfo.ans != null) {
            ans = leftInfo.ans;
        }
        if (rightInfo.ans != null) {
            ans = rightInfo.ans;
        }
        if (ans == null) {
            if (findP && findQ) {
                ans = root;
            }
        }
        return new Info(ans, findP, findQ);
    }

    public static class Info {
        public TreeNode ans;
        public boolean findP;
        public boolean findQ;

        public Info(TreeNode ans, boolean findP, boolean findQ) {
            this.ans = ans;
            this.findP = findP;
            this.findQ = findQ;
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

}
